<template>
	<view class="page">
		<view  class="page-content" :style="{ background: backgroundList[backgroundIndex] }">
			<uni-nav-bar v-show="navShow" dark :fixed="true" shadow :background-color="backgroundList[backgroundIndex]" :color="backgroundList[backgroundIndex] === '#171518' ? 'white' : '#171518'" status-bar left-icon="left" left-text="返回" @clickLeft="backPage"/>
			<view v-show="!navShow" :style="{height: `${statusBarHeight}px`}"></view>
			<!-- 只用来计算内容的高度，不进行展示 -->
			<view id="container" class="hidden">
				<view id="one" :style="{ 
						fontSize: `${fontSize}px`,
						lineHeight: lineHeight
					}" v-html="content">
				</view>
			</view>
			
			<!-- 展示内容的模块 -->
			<view class="wrapper" :style="{ color: backgroundList[backgroundIndex] === '#171518' ? 'white' : '#171518' }"
				@touchstart="onTouchStart" @touchend="onTouchEnd">
				<view id="two" :style="{ 
						fontSize: `${fontSize}px`,
						lineHeight: lineHeight,
						height: `${ innerHeight }px`,
						transform: pageTranslate
					}" v-html="content">
				</view>
			</view>
			
			<view class="footer">
				<view class="footer-site">
					<view class="time">
						<span :style="{color: backgroundList[backgroundIndex] === '#171518' ? 'white' : '#171518'}">{{ nowTime }}</span>
					</view>
					<view class="total-page">
						<span :style="{color: backgroundList[backgroundIndex] === '#171518' ? 'white' : '#171518'}">{{ currentPage === 0 ? 1 : currentPage + 1 }} / {{ totalPage }}</span>
					</view>
					<view class="electricity-level">
						<liiy-battery ref="power"></liiy-battery>
					</view>
				</view>
			</view>
			
			<view>
				<!-- 菜单弹窗 -->
				<uni-popup ref="menu" :background-color="backgroundList[backgroundIndex]" @maskClick="maskMenuClick">
					<uni-grid :column="3" :highlight="true" :showBorder="false" :square="false">
						<uni-grid-item>
							<view class="grid-item-box" :style="{backgroundColor: backgroundList[backgroundIndex]}" @click="chapterShow">
								<text class="iconfont icon-fuhao-yuedu"></text>
								<text class="text" :style="{color: backgroundList[backgroundIndex] === '#171518' ? 'white' : '#171518'}">目录</text>
							</view>
						</uni-grid-item>
						<uni-grid-item @click="ryType">
							<view class="grid-item-box" :style="{backgroundColor: backgroundList[backgroundIndex]}">
								<text :class="sunClass"></text>
								<text class="text" :style="{color: backgroundList[backgroundIndex] === '#171518' ? 'white' : '#171518'}">{{ sunType }}</text>
							</view>
						</uni-grid-item>
						<uni-grid-item>
							<view class="grid-item-box" :style="{backgroundColor: backgroundList[backgroundIndex]}" @click="settingClick">
								<text class="iconfont icon-shezhi"></text>
								<text class="text" :style="{color: backgroundList[backgroundIndex] === '#171518' ? 'white' : '#171518'}">设置</text>
							</view>
						</uni-grid-item>
					</uni-grid>
				</uni-popup>
				<!-- 目录弹窗 -->
				<uni-popup ref="popup" :background-color="backgroundList[backgroundIndex]" @maskClick="maskChapterClick">
					<scroll-view class="popup-content" :scroll-top="scrollTop" scroll-y="true">
						<view class="directory" :style="{background: backgroundList[backgroundIndex], color: backgroundList[backgroundIndex] === '#171518' ? 'white' : '#171518'}">
							<virtual-list :items="chapterData" :size="40" :remain="16" :active="chapterIndex" :scrollHeight="scrollHeight">
								<template v-slot="{ item, active }">
									<view class="directory-listItem" :class="{ active: item.index == active }" @click="showContent(item.chapterId, item.index, 1)">{{ item.chapterName }}</view>
								</template>
							</virtual-list>
						</view>
					</scroll-view>
				</uni-popup>
				<!-- 设置弹窗 -->
				<uni-popup ref="setting" :background-color="backgroundList[backgroundIndex]" @maskClick="maskSettingClick">
					<view class="font-size">
						<view :style="{color: backgroundList[backgroundIndex] === '#171518' ? 'white' : '#171518'}">
							<span>字号</span>
						</view>
						<view class="font-setting">
							<view class="btn" @click="fontReduce" :style="{color: backgroundList[backgroundIndex] === '#171518' ? 'white' : '#171518'}">
								<span>A-</span>
							</view>
							<view :style="{color: backgroundList[backgroundIndex] === '#171518' ? 'white' : '#171518'}">
								<span>{{ fontSize }}</span>
							</view>
							<view class="btn" @click="fontAdd" :style="{color: backgroundList[backgroundIndex] === '#171518' ? 'white' : '#171518'}">
								<span>A+</span>
							</view>
						</view>
					</view>
					<view class="font-size">
						<view class="font-title" :style="{color: backgroundList[backgroundIndex] === '#171518' ? 'white' : '#171518'}">
							<span>背景</span>
						</view>
						<view class="font-setting">
							<view class="bck" v-for="(item, index) in backgroundList" :key="index" :style="{background: item, border: index === backgroundIndex ? '2px solid ' + (backgroundIndex === 4 ? '#ffffff' : '#171518') : ''}" @click="backgroundClick(index)"></view>
						</view>
					</view>
				</uni-popup>
			</view>
		</view>
	</view>
</template>

<script>
	import baseUrl from '@/config/base.js'
	import LiiyBattery from '@/components/liiy-battery/liiy-battery.vue'
	import VirtualList from '@/components/virtualList.vue'
	export default {
		components: {
			LiiyBattery,
			VirtualList
		},
		data() {
			return {
				id: 0,
				windowWidth: 0,
				windowHeight: 0,
				statusBarHeight: 0,
				platform: 0,
				pixelRatio: 0,
				innerHeight: 0,
				fontSize: 16,
				lineHeight: 2,
				currentPage: 0,
				pageTranslate: '',
				startX: 0,
				startY: 0,
				endX: 0,
				endY: 0,
				content: '', // 章节的内容
				chapterData: [], // 章节目录数据
				totalPage: 0, // 单个章节的总页数
				chapterIndex: 0, // 当前所在章节的下标
				nowTime: '',    // 当前时间
				backgroundPage: '#e0d9c6',
				navShow: false,
				yejianShow: true,
				rijianShow: false,
				scrollTop: 0,
				clickable: true,
				scrollHeight: 500,
				backgroundList: ['#ffffff', '#e0d9c6', '#d7e3cb', '#ced8e4', '#171518'],
				backgroundIndex: 1,
				isReturnChapter: false, // 是否返回章节信息
				chapterKey: 'CHAPTER_KEY_', // 章节在缓存中的key
				menuShow: false,
				chapterUrl: '', // 章节网络地址
				bookWebId: '', // 书籍在网络上的ID
				chapterWebId: '', // 章节在网络上的ID
				sunClass: 'iconfont icon-yejianmoshi',
				sunType: '夜间'
			}
		},
		onLoad(options) {
			this.chapterUrl = options.chapterUrl;
			this.bookWebId = options.bookWebId;
			this.chapterWebId = this.getChapterWebId(this.chapterUrl);
			console.log('this.chapterUrl', this.chapterUrl);
			
			// this.id = obj.id
			
			this.setFullScreen(true)
			
			// 获取当前时间
			this.initPage()
			
			// 获取章节和目录的内容
			this.getContentAndChapter()
		},
		onBackPress(e) {
			// console.log('返回监听事件:', e)
			// console.log('书架ID：', this.id)
			// console.log('当前阅读到的章节ID：', this.chapterData[this.chapterIndex].chapterId)
			// console.log('当前阅读到的章节页数：', this.currentPage)
			// 检查是否登录
			const isLogin = this.checkIsLogin();
			if (isLogin) {
				const shelfId = this.id
				const chapterId = this.chapterData[this.chapterIndex].chapterId
				this.backPress(shelfId, chapterId, this.currentPage)
				this.setFullScreen(false)
			} else {
				uni.showModal({
					title: '提示',
					content: '您还没有登录,是否去登录?',
					success(res) {
						if (res.confirm) {
							uni.navigateTo({
								url: '/pages/login/index',
								success() {}
							});
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
				return true;
			}
		},
		computed: {
			
		},
		methods: {
			// 检查是否登录
			checkIsLogin() {
				const token = uni.getStorageSync('token');
				if (!token) {
					return false;
				} else {
					return true;
				}
			},
			// 获取章节在网络上的ID
			getChapterWebId(chapterUrl) {
				console.log('chapterUrl', chapterUrl);
				var chapterUrls = chapterUrl.split('/');
				var lastChapter = chapterUrls[chapterUrls.length - 1];
				return lastChapter.replace('.html', '');
			},
			// 设置全屏
			setFullScreen(type) {
				// #ifdef APP-PLUS || MP-WEIXIN
				plus.navigator.setFullscreen(type)
				// #endif
			},
			// 点击换背景色
			backgroundClick(index) {
				this.backgroundIndex = index
				this.maskSettingClick()
			},
			// 点击设置遮罩事件
			maskSettingClick() {
				this.$refs.setting.close()
				this.$refs.menu.open('bottom')
			},
			// 点击目录遮罩事件
			maskChapterClick() {
				this.$refs.popup.close()
				this.$refs.menu.open('bottom')
			},
			// 日间夜间切换
			ryType() {
				if (this.sunClass === 'iconfont icon-rijianmoshixhdpi') {
					this.sunClass = 'iconfont icon-yejianmoshi';
					this.sunType = '夜间';
					this.backgroundPage = '#d9cebd'
					this.backgroundIndex = 1
				} else {
					this.sunClass = 'iconfont icon-rijianmoshixhdpi';
					this.sunType = '日间';
					this.backgroundPage = '#171518'
					this.backgroundIndex = 4
				}
			},
			// 目录弹框显示
			chapterShow() {
				// console.log('kdald')
				this.$refs.menu.close()
				this.$refs.popup.open('bottom')
			},
			// 设置弹框显示与隐藏
			settingClick() {
				this.$refs.setting.open('bottom')
				this.$refs.menu.close()
			},
			// 点击菜单遮罩层
			maskMenuClick() {
				this.navShow = !this.navShow
				this.$refs.menu.close()
			},
			// 返回上一层
			backPage() {
				// 检查是否登录
				const isLogin = this.checkIsLogin();
				if (isLogin) {
					uni.navigateBack({
					    delta: 1, // 返回的页面数，如果是1表示返回上一级页面，可以根据需求调整
					    success: function () {
					      // console.log('返回上一页成功');
						  const chapterId = this.chapterData[this.chapterIndex].chapterId
						  this.backPress(shelfId, chapterId, this.currentPage)
						  this.setFullScreen(false)
					    },
					    fail: function (error) {
					      // console.error('返回上一页失败', error);
					    }
					})
				} else {
					uni.showModal({
						title: '提示',
						content: '您还没有登录,是否去登录?',
						success(res) {
							if (res.confirm) {
								uni.navigateTo({
									url: '/pages/login/index',
									success() {}
								});
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
				}
			},
			initPage() {
				let _that = this
				// 获取当前时间
				_that.getNowTime()
				setInterval(() => {
					_that.getNowTime()
				}, 60000)
				// 得到电池的电量
				_that.getBattery()
			},
			// 得到电池的电量
			getBattery() {
				let _that = this
				uni.getBatteryInfo({
					success:function(info){
						// console.log('电量百分比: ' + info.level + '%');
						// console.log('是否在充电: ' + (info.isCharging ? '是' : '否'));
						_that.$refs.power.setPower(info.level) // 设置电池电量
						_that.$refs.power.setShan(info.isCharging)
					},
					fail:function(errot){
						console.log(error)
					}
				})
			},
			// 获取当前时间
			getNowTime() {
				let date = new Date();
				let year = date.getFullYear(); // 年
				let month = date.getMonth() + 1; // 月（注意要加1）
				let day = date.getDate(); // 日
				let hours = date.getHours(); // 小时
				let minutes = date.getMinutes(); // 分钟
				let seconds = date.getSeconds(); // 秒数
				if (hours<10) {
					hours = '0' + hours
				}
				if (minutes<10) {
					minutes = '0' + minutes
				}
				this.nowTime = hours + ':' + minutes
			},
			// 返回后将历史数据保存到数据库中
			backPress(shelfId, chapterId, currentPage) {
				// 调用后台接口
				this.$api.post({
					url: '/app/bqg/backPress',
					params: {
						chapterId: chapterId,
						chapterIndex: currentPage
					}
				}).then(res => {
					
				}).catch(error => {
					console.log("fail:" + error)
					uni.hideLoading()
				})
			},
			/**
			 * 第一版：通过书架ID同时查询出章节和所在章节的内容。
			 * NOW 第二版：增加是否查询章节的字段，第一次将章节信息放入缓存中，第二次查询时先看缓存中是否有章节信息，如果有的话，就不需要后台再次返回，反之需要后台返回。
			 */
			showContentAndChapter() {
				const _that = this
				// 判断缓存中是否有章节信息
				let chapterList = uni.getStorageSync(_that.chapterKey + '_' + _that.bookWebId);
				if (!chapterList) {
					_that.isReturnChapter = true;
				}
				return new Promise((resolve, reject) => {
					_that.$api.post({
						url: '/app/bqg/queryChapterAndContent',
						params: {
							chapterWebId: _that.chapterWebId,
							bookWebId: _that.bookWebId,
							isReturnChapter: _that.isReturnChapter
						}
					}).then(res => {
						// console.log('res', res);
						resolve(res.data)
						uni.hideLoading()
					}).catch(error => {
						console.log("fail:" + error)
						uni.hideLoading()
					})
				})
			},
			// 获取章节和目录的内容
			async getContentAndChapter() {
				uni.showLoading({
					title: '查询中,请耐心等待一下!',
					mask: true
				})
				let data = await this.showContentAndChapter()
				await this.doContentAndChapter(data)
				await this.getSystemInfo()
				await this.goToPage(this.currentPage)
			},
			doContentAndChapter(data) {
				this.content = data.content.contentDetail;
				// 判断缓存中是否有章节信息
				const chapterStorageKey = this.chapterKey + '_' + this.bookWebId;
				let chapterList = uni.getStorageSync(chapterStorageKey);
				if (!chapterList) {
					// console.log('chapterList', chapterList)
					// 重新组装章节的数据
					data.chapters.forEach((item, index) => {
						this.chapterData.push({
							index: index,
							chapterName: item.chapterName,
							chapterId: item.id,
							chapterUrl: item.chapterWebHref
						})
						if (data.content.chapterId === item.id) {
							this.chapterIndex = index
							const chapterTitle = '<h2>' + this.chapterData[index].chapterName + '</h2>'
							this.content = chapterTitle + this.content
						}
					})
					uni.setStorageSync(chapterStorageKey, this.chapterData);
				} else {
					this.chapterData = chapterList;
					chapterList.forEach((item, index) => {
						if (data.content.chapterId === item.chapterId) {
							this.chapterIndex = index
							const chapterTitle = '<h2>' + this.chapterData[index].chapterName + '</h2>'
							this.content = chapterTitle + this.content
						}
					})
				}
				// const chapterId = data.userReadChapterId
				const chapterIndex = data.userReadChapterIndex;
				// this.currentPage = chapterIndex
				this.currentPage = 0;
				// 计算本章的总页数
				this.getTotalPage()
			},
			// 获取设备的一些信息
			async getSystemInfo() {
				// console.log(this.content)
				const { windowWidth, windowHeight, statusBarHeight, platform, pixelRatio } = uni.getSystemInfoSync()
				this.windowWidth = windowWidth
				this.windowHeight = windowHeight
				this.pixelRatio = pixelRatio
				this.platform = platform
				this.statusBarHeight = statusBarHeight
				this.innerHeight = windowHeight - statusBarHeight - 20
				
				await this.goToPage(0)
			},
			// 触摸开始
			onTouchStart(event) {
				// 记录触摸开始的坐标
				this.startX = event.touches[0].pageX;
				this.startY = event.touches[0].pageY;
			},
			// 触摸结束
			onTouchEnd(event) {
				// 记录触摸结束的坐标
				this.endX = event.changedTouches[0].pageX;
				this.endY = event.changedTouches[0].pageY;
				
				// 计算屏幕中心坐标
				const screenWidth = uni.getSystemInfoSync().screenWidth;
				const screenHeight = uni.getSystemInfoSync().screenHeight;
				const centerX = screenWidth / 2;
				const centerY = screenHeight / 2;
				
				if (this.startX < (centerX - 40)) {
					// console.log('点击屏幕左边')
					this.toUpPage()
				} else if (this.startX > (centerX + 40)) {
					// console.log('点击屏幕右边')
					this.toNextPage()
				} else if (this.endX > (centerX - 40) && this.endX < (centerX + 40)) {
					// console.log('点击屏幕中间')
					// open 方法传入参数 等同在 uni-popup 组件上绑定 type属性
					this.navShow = true
					this.$refs.menu.open('bottom')
				}
			},
			// 下一页
			toNextPage() {
				this.currentPage ++
				if (this.currentPage === this.totalPage) {
					// 开始进入下一章
					if (this.chapterIndex !== this.chapterData.length - 1) {
						const chapterUrl = this.chapterData[this.chapterIndex +  1].chapterUrl
						this.showContent(chapterUrl, this.chapterIndex +  1, 0)
						this.currentPage = 0
					} else {
						// 已经是最后一章了
						uni.showToast({
							title: '已经是最后一章了',
							icon: 'none',
							duration: 2000
						})
						this.currentPage --
						return
					}
				}
				this.goToPage(this.currentPage)
			},
			// 上一页
			async toUpPage() {
				this.currentPage --
				if (this.currentPage === -1) {
					// 开始计算上一章
					if (this.chapterIndex !== 0) {
						const chapterUrl = this.chapterData[this.chapterIndex -  1].chapterUrl
						await this.showContent(chapterUrl, this.chapterIndex -  1, 0)
						this.currentPage = this.totalPage - 1
					} else {
						// 已经是第一章了
						uni.showToast({
							title: '已经是第一章了',
							icon: 'none',
							duration: 2000
						})
						this.currentPage ++
						return
					}
				}
				this.goToPage(this.currentPage)
			},
			// 跳转到第几页
			goToPage(index) {
				this.pageTranslate = `translateX(-${(this.windowWidth - 16) * index + index}px)`
			},
			// 获取总页数
			getTotalPage() {
				return new Promise((resolve, reject) => {
					// 此处setTimeout 100ms是为了确保元素渲染完毕从而获取正确高度，如果遇到页面页数计算不正确的情况可以增加时间试试看
					setTimeout(() => {
						const query = uni.createSelectorQuery().in(this)
						query.select('#one').boundingClientRect(data => {
							let height = data.height
							// #ifdef APP-PLUS || MP-WEIXIN
							height = Math.round(height * this.pixelRatio) / this.pixelRatio;
							// #endif
							let totalPage = Math.ceil((height + 300) / this.innerHeight) || 1
							this.totalPage = totalPage
							resolve();
						}).exec();
					}, 100);
				});
			},
			async showContent(chapterUrl, index, type) {
				this.chapterIndex = index
				uni.showLoading({
					title: '查询中,请耐心等待一下!',
					mask: true
				})
				let data = await this.getContent(chapterUrl)
				await this.doContent(data.content.contentDetail);
				if (type === 1) {
					this.currentPage = 0
					await this.goToPage(0)
				}
				// 计算本章的总页数
				await this.getTotalPage()
			},
			doContent(content) {
				this.content = '<h2>' + this.chapterData[this.chapterIndex].chapterName + '</h2>' + content
				// console.log("当前内容为：", this.chapterData[this.chapterIndex].chapterName)
			},
			// 通过章节ID获取本章的内容
			getContent(chapterUrl) {
				return new Promise((resolve, reject) => {
					// 调用后台接口
					this.$api.post({
						url: '/app/bqg/getContent',
						params: {
							chapterUrl: chapterUrl
						}
					}).then(res => {
						if (res && res.data.code === 0) {
							resolve(res.data)
						}
						uni.hideLoading()
					}).catch(error => {
						console.log("fail:" + error)
						uni.hideLoading()
					})
				})
			},
			// 字号减
			fontReduce() {
				if (this.fontSize <= 16) {
					return
				}
				this.fontSize -= 2
				this.getTotalPage()
			},
			// 字号加
			fontAdd() {
				if (this.fontSize >= 24) {
					return
				}
				this.fontSize += 2
				this.getTotalPage()
			}
		}
	}
</script>

<style lang="scss">
	
	*,
	view {
		box-sizing: border-box;
	}
	
	.page-content {
		width: 100vw;
		height: 100vh;
	}
	
	#container {
	    position: fixed;
		// z-index: 10;
		opacity: 0;
		margin: 0 16px 0 16px;
	}
	
	.wrapper{
		position: fixed;
	    overflow: hidden;
		margin: 0 16px 20px 16px;
		// background-color: #fff;
	}
	
	#two {
	    columns: calc(100vw - 32px) 1;
	    column-gap: 16px;
	    height: 100%;
	    transition: .4s;
	}
	
	p {
	    text-indent:2em;
	}
	
	.footer {
		position: absolute;
		bottom: 5px;
		left: 16px;
		right: 16px;
		line-height: 15px;
		// width: 100%;
		// background-color: #fff;
		
		.footer-site {
			display: flex;
			justify-content: space-between;
			
			.time {
				float: left;
			}
			
			.total-page {
				margin: 0 auto;
			}
			
			.electricity-level {
				float: right;
			}
		}
	}
	
	.grid-item-box {
		flex: 1;
		// position: relative;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 15px 0;
	}
	
	@mixin flex {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
	}
	
	.popup-content {
		@include flex;
		// align-items: center;
		// justify-content: center;
		padding: 15px;
		height: 500px;
		// background-color: #fff;
		overflow: auto;
	}
	
	.font-size {
		margin-left: 30rpx;
		margin-top: 20rpx;
		margin-bottom: 20rpx;
		display: flex;
		font-size: 16px;
		line-height: 60rpx;
		
		.font-title {
			display: flex;
			align-items: center;
			justify-content: center;
		}
		
		.font-setting {
			display: flex;
			
			.btn {
				margin-left: 20rpx;
				margin-right: 20rpx;
				width: 150rpx;
				height: 60rpx;
				border-radius: 50px / 100px;;
				display: flex;
				align-items: center;
				justify-content: center;
				background: #d4cfb9;
			}
			
			.bck {
				width: 80rpx;
				height: 80rpx;
				border-radius: 50%;
				display: flex;
				align-items: center;
				justify-content: center;
				margin-left: 20rpx;
			}
		}
	}
	
	.chapter-list {
		width: 100%;
		line-height: 40px;
	}
	
	.directory {
		position: absolute;
		top: 0;
		display: flex;
		flex-flow: column;
		width: 100%;
		height: 100%;
		transition: left 0.1s;
		.bookname {
			padding: 20px 0 20px 10px;
			height: 60px;
			font-size: 18px;
		}
		.directory-listItem {
			display: flex;
			align-items: center;
			padding-left: 10px;
			height: 40px;
			font-size: 14px;
			border-bottom: #eee solid 1px;
		}
		.active {
			color: red;
		}
	}
</style>